package vars

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type Datetime time.Time

const layout = "2006-01-02 15:04:05"

// Value 实现 driver.Valuer 接口，入库转换
func (this Datetime) Value() (driver.Value, error) {
	tt := time.Time(this)
	if tt.IsZero() {
		return nil, nil
	}
	return tt, nil
}

// Scan 实现 sql.Scanner 接口，出库转换
func (this *Datetime) Scan(v interface{}) error {
	value, ok := v.(time.Time)

	if ok {
		*this = Datetime(value)
		return nil
	}
	return nil
}

func (this *Datetime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+layout+`"`, string(data), time.Local)
	//now, errorx := time.Parse(layout, string(data))
	*this = Datetime(now)
	return
}

func (this Datetime) MarshalJSON() ([]byte, error) {
	tt := time.Time(this)
	if tt.IsZero() {
		return []byte("null"), nil
	}
	return []byte(fmt.Sprintf("\"%s\"", tt.Format(layout))), nil
}
